package android.aspect;

import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Before;
import org.aspectj.lang.annotation.Pointcut;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Component;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;
import winkyle.woodenfish.android.exception.LoginException;
import winkyle.woodenfish.constant.CookieConstant;
import winkyle.woodenfish.enums.ResultEnum;
import winkyle.woodenfish.util.CookieUtil;

import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;

/**
 * @author winkyle
 * @date 2018/06/22
 * @description api类的访问权限的切面
 */
@Aspect
@Component
public class PermissionAspect {
	private final Logger logger= LoggerFactory.getLogger(PermissionAspect.class);
	
	/**
	 * @description 切所有的api类，除了登录方法不切
	 * @return
	 */
	@Pointcut("execution(public * winkyle.woodenfish.android.api.*.*(..))"+
	"&&!execution(public * winkyle.woodenfish.android.api.UserInfoApi.login(..))")
	public void verifyLogin() {
		// TODO Auto-generated constructor stub
	}
	
	/**
	 * TODO 使用redis保存登录成功的用户，以验证cookie是否合法，增加shiro权限验证，同时判断设备号，登录来源等等
	 * @description 在访问所有的api接口类（除了登录方法）之前，验证是否处于合法登录中，若未处于合法登录中则抛出登录异常
	 * @return
	 */
	@Before(value="verifyLogin()")
	public void beforeVerifyLogin() {
		ServletRequestAttributes servletRequestAttributes = (ServletRequestAttributes) RequestContextHolder.getRequestAttributes();
		HttpServletRequest httpServletRequest = servletRequestAttributes.getRequest();
		Cookie cookie = CookieUtil.get(httpServletRequest, CookieConstant.LONGIN_KEY);
		if(cookie == null) {
			logger.info("用户未登录，无访问权限");
			throw new LoginException(ResultEnum.NOLOGIN);
		}
		//日志打印避免字符串拼接方式浪费资源
		logger.info("登录者是:{}",cookie.getValue());
	}
}
